using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using IWS.SiteManager.Core;

namespace IWS.SiteManager.Web.Controllers
{
	public class ManageController : Controller
	{
		//
		// GET: /Manage/

		Core.Model.ContentRepository _ContentService;
		Core.Model.SiteRepository _SiteService;
		Core.Model.SEOService _SEOService;

		public ManageController()
			: base()
		{
			_ContentService = new IWS.SiteManager.Core.Model.ContentRepository();
			_SiteService = new IWS.SiteManager.Core.Model.SiteRepository();
			_SEOService = new IWS.SiteManager.Core.Model.SEOService();

			SetMasterPage("_Manage");
		}

		public ActionResult Index()
		{
			return View();
		}

		public ActionResult EditSection(string id)
		{
			Core.Model.Section section = null;

			if (!string.IsNullOrEmpty(id))
				section = _ContentService.GetSectionByID(id);

			if (section == null)
				section = new IWS.SiteManager.Core.Model.Section();

			ViewData.Model = section;

			return View();
		}
		[AcceptVerbs(HttpVerbs.Post)]
		public ActionResult SaveSection(string sectionid, string description)
		{
			var section = _ContentService.GetSectionByID(sectionid);
			if (section == null)
				section = new IWS.SiteManager.Core.Model.Section();
			section.ID = sectionid;
			section.Description = description;
			_ContentService.SaveSection(section);

			return RedirectToAction("Sections");
		}
		public ActionResult Sections()
		{
			ViewData.Model = _ContentService.GetAllSections(true);

			return View();
		}
		public ActionResult SectionView(string id)
		{
			var section = _ContentService.GetSectionByID(id);
			section.Pages = _ContentService.GetSectionPages(section.ID);
			ViewData.Model = section;

			Core.SiteManagerContext.Current.CurrentSection = id;

			return View();
		}
		public ActionResult DeleteSection(string id)
		{
			_ContentService.DeleteSection(id);

			return RedirectToAction("Sections");
		}


		public ActionResult Settings()
		{
			ViewData.Model = _SiteService.GetAllSettings();
			return View();
		}
		[AcceptVerbs(HttpVerbs.Post)]
		[ValidateInput(false)]
		public ActionResult Settings(FormCollection collection)
		{
			var settings = _SiteService.GetAllSettings();
			ViewData.Model = settings;

			foreach (var setting in settings)
			{
				var id = string.Format("setting_{0}", setting.ID);
				//get posted value, update, save. 
				if (collection.AllKeys.Contains(id))
				{
					var value = collection[id];
					setting.Value = value;
					_SiteService.SaveSetting(setting);
				}
			}

			Core.SettingCache.ResetCache();

			return View();
		}

		public ActionResult Seo()
		{
			ViewData.Model = _SiteService.GetAllSettings();
			return View();
		}
		[ValidateInput(false)]
		[AcceptVerbs(HttpVerbs.Post)]
		public ActionResult Seo(string sitemap, string GoogleWebmasterToolsVerifyType, string GoogleWebmasterToolsValue, string GoogleAnalyticsID)
		{
			//save the sitemap filename. 
			var sitemap_file = SettingCache.Current.GetSetting(Core.Constants.SitemapOutputFile);
			sitemap_file.Value = sitemap;
			_SiteService.SaveSetting(sitemap_file);

			//google web master type
			var gwmType_setting = SettingCache.Current.GetSetting(Core.Constants.GoogleWebMasterType);
			gwmType_setting.Value = GoogleWebmasterToolsVerifyType.Trim();
			_SiteService.SaveSetting(gwmType_setting);

			//google web master value
			var gwmValue_setting = SettingCache.Current.GetSetting(Core.Constants.GoogleWebMasterValue);
			gwmValue_setting.Value = GoogleWebmasterToolsValue;
			_SiteService.SaveSetting(gwmValue_setting);

			//google analytics id
			var gaID_setting = SettingCache.Current.GetSetting(Core.Constants.GoogleAnalyticsID);
			gaID_setting.Value = GoogleAnalyticsID;
			_SiteService.SaveSetting(gaID_setting);

			//refresh cache
			SettingCache.ResetCache();

			int gwmTypeID = (int)Core.GoogleWebMasterType.MetaTag;
			if (int.TryParse(gwmType_setting.Value, out gwmTypeID) && gwmTypeID == (int)Core.GoogleWebMasterType.File)
			{
				//if it's file, then regen the file if it doesn't exist. 
				_SiteService.GenerateGoogleWebMasterFile(Server.MapPath("~/"), gwmValue_setting.Value);
			}

			//reset model
			ViewData.Model = _SiteService.GetAllSettings();

			return View();
		}


		public ActionResult DeleteContent(string id)
		{
			int pid = 0;
			int.TryParse(id, out pid);

			var section = _ContentService.GetSectionIDForPage(pid);
			_ContentService.DeleteContent(pid);

			return RedirectToAction("SectionView", new { id = section });
		}
		public ActionResult EditContent(string id)
		{
			int pid = 0;
			int.TryParse(id, out pid);
			var page = _ContentService.GetContent(pid);

			if (page == null)
			{
				page = new IWS.SiteManager.Core.Model.Content();

				string sectionID = Request["section"];
				string permalink = Request["permalink"];

				if (!string.IsNullOrEmpty(sectionID))
				{
					Core.SiteManagerContext.Current.CurrentSection = sectionID;
					page.SectionID = sectionID;
				}
				else if (!string.IsNullOrEmpty(Core.SiteManagerContext.Current.CurrentSection))
					page.SectionID = Core.SiteManagerContext.Current.CurrentSection;

				if (!string.IsNullOrEmpty(permalink))
				{
					page.Permalink = permalink;
					page.Title = permalink.Replace('-', ' ');
				}
			}
			else
			{
				//if this is the first hit, load the current section using this page. 
				if (string.IsNullOrEmpty(Core.SiteManagerContext.Current.CurrentSection) || page.SectionID != Core.SiteManagerContext.Current.CurrentSection)
					Core.SiteManagerContext.Current.CurrentSection = page.SectionID;
			}

			//core data. 
			ViewData.Model = page;

			var options = (from section in _ContentService.GetQueryableSections()
								select new SelectListItem() { Selected = false, Text = section.ID, Value = section.ID }).ToList();
			ViewData["Options"] = options;


			var sectionDefault = false;

			if (!string.IsNullOrEmpty(page.SectionID))
			{
				var section = _ContentService.GetSectionByID(page.SectionID);
				if (section != null)
					sectionDefault = !section.DefaultContentID.HasValue || section.DefaultContentID == page.ID;
				else
					sectionDefault = true;
			}
			else
				sectionDefault = true;

			ViewData["SectionDefault"] = sectionDefault;

			return View();
		}
		[ValidateInput(false)]
		[AcceptVerbs(HttpVerbs.Post)]
		public ActionResult EditContent(string title, string permalink, string id, string sectionid, string tags, string body, string head, string metadescription, string metakeywords, string defaultpage)
		{
			Core.Model.Content content = null;
			//reload viewdata. 
			if (string.IsNullOrEmpty(id))
				content = new IWS.SiteManager.Core.Model.Content() { ContentTypeID = (int)Core.ContentType.Page, Title = title, Permalink = permalink, SectionID = sectionid, Tags = tags, Body = body, Head = head, MetaDescription = metadescription, MetaKeywords = metadescription };
			else
			{
				content = _ContentService.GetContent(Convert.ToInt32(id));
				content.SectionID = sectionid;
				content.Title = title;
				content.Permalink = permalink;
				content.Tags = tags;
				content.Body = body;
				content.Head = head;
				content.MetaDescription = metadescription;
				content.MetaKeywords = metakeywords;
			}

			if (!ValidateEditContent(title, permalink, id, sectionid, tags, body, head, metadescription, metakeywords))
				return View("EditContent", content);

			//otherwise
			//good, save. 

			_ContentService.SaveContent(content);

			if (defaultpage.Trim().ToLower() == "true")
			{
				var section = _ContentService.GetSectionByID(content.SectionID);
				section.DefaultContentID = content.ID;
				_ContentService.SaveSection(section);
			}

			_ContentService.WriteSitemap(Server.MapPath("~/"));

			return RedirectToAction("SectionView", "Manage", new { id = Core.SiteManagerContext.Current.CurrentSection });
		}

		bool ValidateEditContent(string title, string permalink, string id, string sectionid, string tags, string body, string head, string metadescription, string metakeywords)
		{
			Dictionary<string, string> errors = new Dictionary<string, string>();

			if (string.IsNullOrEmpty(sectionid))
				errors.Add("section", "Section required");

			if (string.IsNullOrEmpty(title))
				errors.Add("title", "Title required");

			if (string.IsNullOrEmpty(permalink))
				errors.Add("permalink", "Permalink required.");

			foreach (var error in errors)
			{
				ModelState.AddModelError(error.Key, error.Value);
			}

			return errors.Count == 0;
		}

		void SetMasterPage(string section)
		{
			ViewData[Core.Constants.ViewDataMasterPageFile] = string.Format(Core.Constants.SiteMasterLocationFormatString, section);
		}
	}
}
